package com.crois.barrier.web.plugin;

import com.crois.barrier.common.dto.ApiRouteInfo;
import com.crois.barrier.common.dto.PluginData;
import com.crois.barrier.plugin.BarrierPlugin;
import com.crois.barrier.plugin.BarrierPluginChain;
import com.crois.barrier.web.cache.CacheManager;
import com.crois.barrier.web.support.ServerWebExchangeUtils;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Hou Ze Yu
 * @description 抽象Door插件
 * @date 2020/7/12
 */
@RequiredArgsConstructor
public abstract class AbstractBarrierPlugin implements BarrierPlugin {

    private static  final Logger LOGGER = LoggerFactory.getLogger(AbstractBarrierPlugin.class);

    private final CacheManager cacheManager;

    /***
     * 模版方法
     * @param exchange
     * @param chain
     * @param routeInfo
     * @return
     */
    protected abstract Mono<Void> doExecute(ServerWebExchange exchange, BarrierPluginChain chain, ApiRouteInfo routeInfo);

    @Override
    public Mono<Void> execute(ServerWebExchange exchange, BarrierPluginChain chain) {
        String pluginName = name();
        PluginData pluginData = cacheManager.findPluginByName(pluginName);
        ApiRouteInfo routeInfo = (ApiRouteInfo) exchange.getAttributes().get(ServerWebExchangeUtils.BARRIER_ROUTE_ATTR);
        if (pluginData!=null&&pluginData.getEnabled()){
            return  doExecute(exchange,chain,routeInfo);
        }
        return chain.execute(exchange);
    }


}
